package apps.softtech.Utility;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;
/**
 * Queue item
 * 
 * @author tdPhuoc
 * 
 */
public class QueueItem {

	final String URL_KEY = "url";
	final String DATA_KEY = "data";
	final String QUERY_KEY = "query_key";

	private String url;
	private String data;
	private String query;

	QueueItem(String url, String data , String query) {
		this.url = url;
		this.data = data;
		this.query = query;
	}

	QueueItem(JSONObject jObject) {
		try {
			url = jObject.getString(URL_KEY);
			data = jObject.getString(DATA_KEY);
			query = jObject.getString(QUERY_KEY);
		} catch (Exception e) {

		}
	}

	QueueItem() {
		this("", "" , "");
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getData() {
		return data;
	}

	public void setData(String data) {
		this.data = data;
	}

	public String getQuery() {
		return query;
	}

	public void setQuery(String query) {
		this.query = query;
	}

	public JSONObject toJSONObject() {
		JSONObject jObject = new JSONObject();
		try {
			jObject.put(URL_KEY, this.url);
			jObject.put(DATA_KEY, this.data);
			jObject.put(QUERY_KEY, this.query);
		} catch (Exception e) {

		}
		return jObject;

	}

	public ArrayList<NameValuePair> toValuePair(){
		ArrayList<NameValuePair> pairList = new ArrayList<NameValuePair>();
		pairList.add(new BasicNameValuePair(DATA_KEY, data));
		return pairList;
	}
	
	public String toJSONString() {
		return toJSONObject().toString();
	}
	
	public void submitToServer(final Context context){
		AsyncTask<Void, Void, String> taskSubmitToServer = new AsyncTask<Void, Void, String>(){

			@Override
			protected String doInBackground(Void... params) {
				HttpRequest request = new HttpRequest();
				return request.makeServiceCall(url, HttpRequest.POST, toValuePair());
			}

			@Override
			protected void onPostExecute(String result) {
				try{
					JSONObject object = new JSONObject(result);
					int success = object.getInt(ApplicationConstants.FIELD_SUCCESS);
					if(success == 1){
//						DatabaseHandler db = new DatabaseHandler(context);
//						db.excuteQuery(query);
					}
					
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			
		};
		taskSubmitToServer.execute(null,null,null);
	}
	
}
